"""
Text file parser for plain text files
"""
from pathlib import Path
from typing import Dict, Any, Union
from .base import FileParser, ParseResult
import time

class TextParser(FileParser):
    """Parser for plain text files"""
    
    def parse(self, file_path: Union[str, Path]) -> ParseResult:
        """Parse a plain text file"""
        start_time = time.time()
        file_path = Path(file_path)
        
        # Validate file
        if not self.validate_file(file_path):
            return self.create_error_result("File validation failed", file_path)
        
        try:
            # Read the text file
            with open(file_path, 'r', encoding='utf-8', errors='replace') as f:
                content = f.read()
            
            # Basic metadata
            metadata = {
                "file_size": file_path.stat().st_size,
                "encoding": "utf-8",
                "line_count": len(content.split('\n')),
                "char_count": len(content),
                "processing_time_ms": (time.time() - start_time) * 1000
            }
            
            return ParseResult(
                success=True,
                content=content,
                file_type=self.get_file_type(),
                metadata=metadata,
                error=None
            )
        
        except UnicodeDecodeError:
            # Try with latin-1 encoding if UTF-8 fails
            try:
                with open(file_path, 'r', encoding='latin-1') as f:
                    content = f.read()
                
                metadata = {
                    "file_size": file_path.stat().st_size,
                    "encoding": "latin-1",
                    "line_count": len(content.split('\n')),
                    "char_count": len(content),
                    "processing_time_ms": (time.time() - start_time) * 1000
                }
                
                return ParseResult(
                    success=True,
                    content=content,
                    file_type=self.get_file_type(),
                    metadata=metadata,
                    error=None
                )
            except Exception as e:
                return self.create_error_result(f"Failed to read text file: {str(e)}", file_path, start_time)
        
        except Exception as e:
            return self.create_error_result(f"Failed to parse text file: {str(e)}", file_path, start_time)
    
    def get_file_type(self):
        """Return the file type this parser handles"""
        from .base import FileType
        return FileType.PLAIN_TEXT
    
    def supports_file_type(self, file_type):
        """Check if parser supports the given file type"""
        from .base import FileType
        return file_type == FileType.PLAIN_TEXT
    
    def get_supported_extensions(self):
        """Return supported file extensions"""
        return ['.txt', '.log', '.cfg', '.conf', '.ini']
    
    def get_supported_mime_types(self):
        """Return supported MIME types"""
        return ['text/plain', 'text/x-log', 'text/x-ini']